const { mysql } = require('../config');
const mysqlLib = require('mysql');
const logUtil = require('./log_util');

const pool = mysqlLib.createPool(mysql);

pool.on('release', (connection) => {
  logUtil.debug('Connection %d released', connection.threadId);
});
pool.on('connection', (connection) => {
  logUtil.debug('Connection %d connected', connection.threadId);
});
const util = {
  execute(sql) {
    return new Promise((res, rj) => {
      logUtil.info('[select] sql is \n', sql);
      pool.query(sql, (error, results) => {
        if (error) {
          rj(error);
        } else {
          // logUtil.debug('[select] sql results ', results);
          res(JSON.parse(JSON.stringify(results)));
        }
      });
    });
  }
};

module.exports = util;
